import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

import Home from '@/views/Home'
import Topic from '@/views/Topic'
import Category from '@/views/Category'
import Cart from '@/views/Cart'
import User from '@/views/User'
import Search from '@/views/Search'
import Details from '@/views/Details'

//配置路由routes规则
const routes = [
    {path:'/',redirect:'/home'},
    {path:'/home',component:Home,name:"home",meta:{ isShowTabbar: true}},
    {path:'/topic',component:Topic,name:"topic",meta:{ isShowTabbar: true}},
    {path:'/category',component:Category,name:"category",meta:{ isShowTabbar: true}},
    {path:'/cart',component:Cart,name:"cart"  ,meta:{ isShowTabbar: true}},
    {path:'/user',component:User,name:"user",meta:{ isShowTabbar: true}},
    {path:'/search',component:Search,name:"search",meta:{ isShowTabbar: false}},
    {path:'/details',component:Details,name:"details",meta:{ isShowTabbar: false}},
]

//创建路由实例对象
const router = new VueRouter({
    mode:'history',

    //将配置好的路由规则挂载到router路由实例对象 再将router路由实例对象挂载到vue实例对象
    routes
})

//在vue-router在3.1.0版本之后，push和replace方法会返回一个promise对象，如果跳转到相同的路由，
// 就报promise uncaught异常
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
    return originalPush.call(this, location).catch((err) => err);
};

//全局路由守卫
router.beforeEach((to, from, next) => {
    if (to.path == '/cart') {
        // 判断登录状态
        let token = localStorage.getItem('token')
        if (token) {
            // token存在
            next()
        } else {
            // token不存在
            // console.log(Vue.prototype); // vueComponent
            // 1. 提示用户
            Vue.prototype.$toast({
                type: 'fail',
                message: '请先登录',
                duration: 2000
            })
            // 2.跳转到我的页
            setTimeout(() => {
                next('/user')
            }, 2000)
        }
    } else {
        next()
    }
})
    
export default router
    

